package vashion.azeroth.core.service.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import vashion.azeroth.common.encrypt.Md5Encrypt;
import vashion.azeroth.common.im.AppKeys;
import vashion.azeroth.common.im.LoginSH256Util;
import vashion.azeroth.common.member.GeneralNickUtil;
import vashion.azeroth.common.type.check.TypeCheck;
import vashion.azeroth.contant.AzerothConstants;
import vashion.azeroth.contant.GenericErrorEnum;
import vashion.azeroth.contant.InviteErrorEnum;
import vashion.azeroth.contant.MemberErrorEnum;
import vashion.azeroth.core.manager.personal.PersonalFriendManager;
import vashion.azeroth.core.manager.personal.PersonalInviteCodeManager;
import vashion.azeroth.core.manager.personal.PersonalMemberManager;
import vashion.azeroth.core.personal.pojo.PersonalInviteCode;
import vashion.azeroth.core.personal.pojo.PersonalMember;
import vashion.azeroth.core.personal.pojo.PersonalMemberToken;
import vashion.azeroth.core.result.ApiResult;
import vashion.azeroth.core.service.PersonalMemberService;
import vashion.azeroth.core.service.PersonalMemberTokenService;
import vashion.azeroth.core.service.base.BaseService;

import com.alibaba.fastjson.JSON;

@Service
public class PersonalMemberServiceImpl extends BaseService implements PersonalMemberService<PersonalMember> {

	private static final Logger log = LoggerFactory.getLogger(PersonalMemberServiceImpl.class);

	@Autowired
	private PersonalMemberManager personalMemberManager;

	@Autowired
	private PersonalInviteCodeManager inviteCodeManager;

	@Autowired
	private PersonalMemberTokenService<PersonalMemberToken> memberTokenService;
	@Autowired
	private PersonalFriendManager friednManager;

	@Value("#{settings['customerService']}")
	private Long customerService;

	public ApiResult<PersonalMember> login(PersonalMember memberParam) {

		PersonalMember member = personalMemberManager.getMemberByName(memberParam.getMemberName());
		// 用户不存在
		if (null == member) {
			return ApiResult.newErrorResult(GenericErrorEnum.NOT_EXIST.getErrorCode(),
					"用户" + GenericErrorEnum.NOT_EXIST.getErrorMessage());
		}

		// 密码错误
		if (!Md5Encrypt.encrypt(memberParam.getMemberPwd(), "UTF-8").equals(member.getMemberPwd())) {
			return ApiResult.newErrorResult(MemberErrorEnum.PWD_INCORRECT.getErrorCode(),
					"用户" + MemberErrorEnum.PWD_INCORRECT.getErrorMessage());
		}

		// 验证账号是否有效
		if (null == member.getStatus()
				|| member.getStatus() != AzerothConstants.PersonalMember.PersonalMemberState.enable) {
			return ApiResult.newErrorResult(GenericErrorEnum.NOT_EXIST.getErrorCode(),
					"用户" + GenericErrorEnum.NOT_EXIST.getErrorMessage());
		}
		// 生成token
		PersonalMemberToken token = memberTokenService.createOrUpdateToken(member);

		member.setToken(token.getAccessToken());
		member.setCustomerService(customerService);

		// 为推送通知，保存设备的RegistrationId
		if (null != memberParam.getRegistrationId()) {
			member.setRegistrationId(memberParam.getRegistrationId());
			personalMemberManager.updateRegistrationId(member);
		}

		PersonalInviteCode inviteCode = inviteCodeManager.getInviteCodeByUseMemberName(member.getMemberName());
		if (null != inviteCode) {
			member.setInviteCode(inviteCode.getCode());
		}
		
		/*------ im签名逻辑 start-----*/
		String appKey = AppKeys.VASHION_IOS_APPKEYS;
		String appSecret = AppKeys.VASHION_IOS_SECRET;

		LoginSH256Util.ImSignModel imSignModel = LoginSH256Util.getLoginModel(appKey, appSecret,
				Long.valueOf(member.getMemberId()));
		member.setImSignModel(imSignModel);
		/*------ im签名逻辑 end-----*/
		
		

		return ApiResult.newSuccessResult(member);
	}

	@Override
	public ApiResult<PersonalMember> register(PersonalMember memberParam) {

		PersonalMember resultMember = personalMemberManager.getMemberByName(memberParam.getMemberName());

		if (null != resultMember) {
			return ApiResult.newErrorResult(MemberErrorEnum.EXIXTID.getErrorCode(),
					MemberErrorEnum.EXIXTID.getErrorMessage());
		}

		PersonalInviteCode inviteCode = new PersonalInviteCode();
		inviteCode.setCode(memberParam.getInviteCode());
		inviteCode = inviteCodeManager.getInviteCodeByCode(inviteCode);

		if (null == inviteCode) {
			return ApiResult.newErrorResult(GenericErrorEnum.NOT_EXIST.getErrorCode(),
					"邀请码" + GenericErrorEnum.NOT_EXIST.getErrorMessage());
		} else if (inviteCode.getStatus() == AzerothConstants.PersonalInviteCode.PersonalInviteCodeStatus.used) {
			return ApiResult.newErrorResult(InviteErrorEnum.USED.getErrorCode(),
					"邀请码" + InviteErrorEnum.USED.getErrorMessage());
		} else {
			// 设置为代理商
			memberParam.setNickName(GeneralNickUtil.generalNickName("", 8));
			memberParam.setType(AzerothConstants.PersonalMember.MemberType.agent);
			resultMember = createMember(memberParam, inviteCode);

			inviteCode.setUseMemberName(memberParam.getMemberName());
			inviteCode.setStatus(AzerothConstants.PersonalInviteCode.PersonalInviteCodeStatus.used);
			inviteCode.setTimeUsed(new Date());
			inviteCodeManager.update(inviteCode);
		}

		return ApiResult.newSuccessResult();
	}

	/**
	 * 注册用户
	 * 
	 * @param memberParam
	 * @param inviteCode
	 * @return
	 */
	private PersonalMember createMember(PersonalMember memberParam, PersonalInviteCode inviteCode) {
		memberParam.setStatus(AzerothConstants.PersonalMember.PersonalMemberState.enable);
		memberParam.setTimeAdd(new Date());
		memberParam.setTimeEdit(new Date());
		memberParam.setMemberPwd(Md5Encrypt.encrypt(memberParam.getMemberPwd(), "UTF-8"));
		if (null != inviteCode) {
			memberParam.setInviteMemberId(inviteCode.getMemberId());
			memberParam.setInviteMemberName(inviteCode.getMemberName());
		}

		return personalMemberManager.save(memberParam);
	}

	/**
	 * 创建人脉
	 * 
	 * @param resultMember
	 * @param inviteCode
	 */
	// private void createFriend(PersonalMember resultMember, PersonalInviteCode
	// inviteCode) {
	// PersonalFriend param = new PersonalFriend();
	// param.setMemberId(resultMember.getMemberId());
	// param.setMemberName(resultMember.getMemberName());
	// param.setInviteMemberId(inviteCode.getMemberId());
	// param.setInviteMemberName(inviteCode.getMemberName());
	// friednManager.save(param);
	// }

	/**
	 * 判断是否为会员按照三个维度：memberName，memberId，mobile_phone 参数都传入时如果有一个不符，则认为不是会员，
	 * 可以只有一个校验维度，但至少有一个校验维度
	 * 
	 */

	public ApiResult<PersonalMember> checkMember(PersonalMember member) {

		ApiResult<PersonalMember> result = new ApiResult<PersonalMember>();
		if (null != member.getMemberId() || null != member.getMobilePhone() || null != member.getMemberName()) {
			if (personalMemberManager.find(member).size() > 0) {
				result = ApiResult.newSuccessResult();
			} else {
				result = ApiResult.newErrorResult(MemberErrorEnum.NOT_EXISTID.getErrorCode(),
						MemberErrorEnum.NOT_EXISTID.getErrorMessage());
			}
		} else {
			return ApiResult.newErrorResult(MemberErrorEnum.NOT_EXISTID.getErrorCode(),
					MemberErrorEnum.NOT_EXISTID.getErrorMessage());
		}

		return result;
	}

	public ApiResult<PersonalMember> findPwd(String newPwd, String memberName) {
		PersonalMember memberDb = personalMemberManager.getMemberByName(memberName);
		if (null == memberDb) {
			return ApiResult.newErrorResult(GenericErrorEnum.NOT_EXIST.getErrorCode(),
					"用户" + GenericErrorEnum.NOT_EXIST.getErrorMessage());
		}
		memberDb.setMemberPwd(Md5Encrypt.encrypt(newPwd, "UTF-8"));
		memberDb.setTimeEdit(new Date());
		int count = personalMemberManager.update(memberDb);
		if (count > 0) {
			return ApiResult.newSuccessResult();
		} else {
			return ApiResult.newErrorResult(MemberErrorEnum.UPDATE_PWD_FAILED.getErrorCode(),
					MemberErrorEnum.UPDATE_PWD_FAILED.getErrorMessage());
		}
	}

	public ApiResult<PersonalMember> updatePwd(String oldPwd, String newPwd, Long memberId) {

		if (oldPwd.equals(newPwd)) {
			return ApiResult.newErrorResult(MemberErrorEnum.OLDPWD_SAME_NEWPWD.getErrorCode(),
					MemberErrorEnum.OLDPWD_SAME_NEWPWD.getErrorMessage());
		}

		String expOldPwd = personalMemberManager.findOldPwd(memberId); // 获取DB中旧密码
		String md5Pwd = Md5Encrypt.encrypt(oldPwd, "UTF-8"); // 客户端上传和旧密码加密
		if (!expOldPwd.equals(md5Pwd)) {
			return ApiResult.newErrorResult(MemberErrorEnum.OLDPWD_INCORRECT.getErrorCode(),
					MemberErrorEnum.OLDPWD_INCORRECT.getErrorMessage());
		} else {
			PersonalMember member = new PersonalMember();
			member.setTimeEdit(new Date());
			String md5NewPwd = Md5Encrypt.encrypt(newPwd, "UTF-8");
			member.setMemberPwd(md5NewPwd);
			member.setMemberId(memberId);
			int count = personalMemberManager.update(member);
			if (count > 0) {
				return ApiResult.newSuccessResult();
			} else {
				return ApiResult.newErrorResult(MemberErrorEnum.UPDATE_PWD_FAILED.getErrorCode(),
						MemberErrorEnum.UPDATE_PWD_FAILED.getErrorMessage());
			}
		}
	}

	@Override
	public int findCnt(PersonalMember member) {
		int count = personalMemberManager.findCnt(member);
		return count;
	}

	@Override
	public ApiResult<Map<String, Object>> findInvitedMember(PersonalMember member) {
		Integer count = personalMemberManager.findCnt(member);

		initPages(member, count);

		List<PersonalMember> memberList = personalMemberManager.find(member);
		Map<String, Object> map = new HashMap<String, Object>();

		// 未邀请过用户
		map.put("count", count);
		if (null == memberList) {
			map.put("dataList", null);
			return ApiResult.newSuccessResult();
		}

		map.put("dataList", memberList);
		return ApiResult.newSuccessResult(map);
	}

	@Override
	public PersonalMember getMemberByNick(String nickName) {
		return personalMemberManager.getMemberByNick(nickName);
	}

	@Override
	public ApiResult<PersonalMember> autoLogin(PersonalMember memberParam) {
		PersonalMember member = personalMemberManager.get(memberParam.getMemberId());
		if (null == member) {
			return ApiResult.newErrorResult(GenericErrorEnum.NOT_EXIST.getErrorCode(),
					GenericErrorEnum.NOT_EXIST.getErrorMessage());
		}

		PersonalMemberToken token = memberTokenService.getMemberToken(memberParam.getMemberId());

		if (!token.getAccessToken().equals(memberParam.getToken())) {
			return ApiResult.newErrorResult(MemberErrorEnum.ACCESS_TOKEN_ERROR.getErrorCode(),
					MemberErrorEnum.ACCESS_TOKEN_ERROR.getErrorMessage());
		}

		if (DateUtils.truncatedCompareTo(token.getAccessTokenTimeOut(), new Date(), Calendar.SECOND) < 0) {
			return ApiResult.newErrorResult(MemberErrorEnum.ACCESS_TOKEN_TIME_OUT.getErrorCode(),
					MemberErrorEnum.ACCESS_TOKEN_TIME_OUT.getErrorMessage());
		}

		member.setToken(token.getAccessToken());
		member.setCustomerService(customerService);

		PersonalInviteCode inviteCode = inviteCodeManager.get(member.getMemberId());
		if (null != inviteCode) {
			member.setInviteCode(inviteCode.getCode());
		}

		String appKey = AppKeys.VASHION_IOS_APPKEYS;
		String appSecret = AppKeys.VASHION_IOS_SECRET;

		LoginSH256Util.ImSignModel imSignModel = LoginSH256Util.getLoginModel(appKey, appSecret,
				Long.valueOf(member.getMemberId()));
		member.setImSignModel(imSignModel);

		return ApiResult.newSuccessResult(member);
	}

	@Override
	public ApiResult<PersonalMember> modifyMember(PersonalMember memberParam) {
		// PersonalMember member =
		// personalMemberManager.getMemberByNick(memberParam.getMemberName());
		// if(null != member) {
		// return
		// ApiResult.newErrorResult(MemberErrorEnum.EXIXTED_NICK.getErrorCode(),
		// MemberErrorEnum.EXIXTED_NICK.getErrorMessage());
		// }

		PersonalMember member = personalMemberManager.get(memberParam.getMemberId());
		if (null == member) {
			return ApiResult.newErrorResult(GenericErrorEnum.NOT_EXIST.getErrorCode(),
					GenericErrorEnum.NOT_EXIST.getErrorMessage());
		}

		// memberParam.setMemberId(memberParam.getMemberId());

		int count = personalMemberManager.update(memberParam);
		if (count > 0) {
			return ApiResult.newSuccessResult();
		}

		return ApiResult.newErrorResult(GenericErrorEnum.UPDATE_ERROR.getErrorCode(),
				GenericErrorEnum.UPDATE_ERROR.getErrorMessage());
	}

	public ApiResult<PersonalMember> handlePayPwd(Long memberId, String type, String newPwd) {

		if (!TypeCheck.checkPayPwd(type)) {
			return ApiResult.newErrorResult(GenericErrorEnum.PARAMETER_ERROR.getErrorCode(),
					GenericErrorEnum.PARAMETER_ERROR.getErrorMessage());
		}

		if (StringUtils.isBlank(newPwd)) {
			return ApiResult.newErrorResult(GenericErrorEnum.NOT_EMPTY.getErrorCode(),
					"新密码" + GenericErrorEnum.NOT_EMPTY.getErrorMessage());
		}

		PersonalMember member = personalMemberManager.get(memberId);
		if (null == member) {
			return ApiResult.newErrorResult(GenericErrorEnum.NOT_EXIST.getErrorCode(),
					GenericErrorEnum.NOT_EXIST.getErrorMessage());
		}

		PersonalMember paramMember = new PersonalMember();
		paramMember.setMemberId(memberId);
		paramMember.setPayPwd(Md5Encrypt.encrypt(newPwd, "UTF-8"));
		int count = personalMemberManager.update(paramMember);

		if (count > 0)
			return ApiResult.newSuccessResult();

		return ApiResult.newErrorResult(GenericErrorEnum.UPDATE_ERROR.getErrorCode(),
				GenericErrorEnum.UPDATE_ERROR.getErrorMessage());
	}

	@Override
	public ApiResult<String> checkPayPwd(Long memberId, String pwd) {
		if (StringUtils.isBlank(pwd)) {
			return ApiResult.newErrorResult(GenericErrorEnum.NOT_EMPTY.getErrorCode(),
					"支付密码" + GenericErrorEnum.NOT_EMPTY.getErrorMessage());
		}

		PersonalMember member = personalMemberManager.get(memberId);
		if (null != member && member.getPayPwd().equals(Md5Encrypt.encrypt(pwd, "UTF-8")))
			return ApiResult.newSuccessResult();

		return ApiResult.newErrorResult(MemberErrorEnum.PAY_PWD_ERROR.getErrorCode(),
				MemberErrorEnum.PAY_PWD_ERROR.getErrorMessage());
	}

	public static void main(String args[]) {
		StringBuffer appSecret = new StringBuffer("SBpv7dgv2O18BNGwKzbtfvoPWrTjXy9X");
		StringBuffer appKey = new StringBuffer("55b5729ffbbf175249b2b56ca431445f");
		PersonalMember member = new PersonalMember();
		LoginSH256Util.ImSignModel imSignModel = LoginSH256Util.getLoginModel(appKey.toString(), appSecret.toString(),
				Long.valueOf(123));
		member.setImSignModel(imSignModel);
		System.out.println(JSON.toJSONString(member));
	}

	@Override
	public ApiResult<PersonalMember> backLogin(PersonalMember backMember) {

		PersonalMember member = personalMemberManager.getMemberByName(backMember.getMemberName());
		if (null == member) {
			return ApiResult.newErrorResult(GenericErrorEnum.NOT_EXIST.getErrorCode(),
					"用户" + GenericErrorEnum.NOT_EXIST.getErrorMessage());
		}

		if (member.getType() != AzerothConstants.PersonalMember.MemberType.back) {
			return ApiResult.newErrorResult(GenericErrorEnum.NOT_EXIST.getErrorCode(),
					"用户" + GenericErrorEnum.NOT_EXIST.getErrorMessage());
		}

		if (!member.getMemberPwd().equals(Md5Encrypt.encrypt(backMember.getMemberPwd(), "UTF-8"))) {
			return ApiResult.newErrorResult(MemberErrorEnum.INCORRECT.getErrorCode(),
					"密码" + MemberErrorEnum.INCORRECT.getErrorMessage());
		}

		return ApiResult.newSuccessResult(member);
	}

	@Override
	public ApiResult<PersonalMember> backRegister(PersonalMember member) {
		PersonalMember backMember = new PersonalMember();
		backMember.setMemberName(member.getMemberName());
		backMember.setMemberPwd(Md5Encrypt.encrypt(member.getMemberPwd(), "UTF-8"));
		backMember.setStatus(AzerothConstants.PersonalMember.PersonalMemberState.enable);
		backMember.setType(AzerothConstants.PersonalMember.MemberType.supplier);
		backMember.setSrc("后台注册");
		backMember.setTimeAdd(new Date());

		PersonalMember dbMember = personalMemberManager.save(backMember);

		if (null == dbMember) {
			return ApiResult.newErrorResult(GenericErrorEnum.INSERT_ERROR.getErrorCode(),
					GenericErrorEnum.INSERT_ERROR.getErrorMessage());
		}

		return ApiResult.newSuccessResult(dbMember);
	}

	public ApiResult<List<PersonalMember>> getAdminList() {

		List<PersonalMember> personalMemberList = personalMemberManager.getAdminList();
		return ApiResult.newSuccessResult(personalMemberList);
	}

	@Override
	public PersonalMember get(Long memberId) {
		return personalMemberManager.get(memberId);
	}
}
